package org.jeecg.modules.zcgl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.ReflectHelper;
import org.jeecg.modules.activiti.enums.ResultEnum;
import org.jeecg.modules.system.mapper.SysConfigMapper;
import org.jeecg.modules.system.service.IEncodingRulesService;
import org.jeecg.modules.zcgl.entity.AssetImage;
import org.jeecg.modules.zcgl.entity.AssetInfo;
import org.jeecg.modules.zcgl.entity.AssetInfoSub;
import org.jeecg.modules.zcgl.enums.AssetStatusEnum;
import org.jeecg.modules.zcgl.enums.YesNoEnum;
import org.jeecg.modules.zcgl.mapper.AssetImageMapper;
import org.jeecg.modules.zcgl.mapper.AssetInfoMapper;
import org.jeecg.modules.zcgl.mapper.AssetInfoSubMapper;
import org.jeecg.modules.zcgl.mapper.CustomerInfoMapper;
import org.jeecg.modules.zcgl.service.IAssetContractLogService;
import org.jeecg.modules.zcgl.service.IAssetInfoService;
import org.jeecg.modules.zcgl.service.IAssetInfoSubService;
import org.jeecg.modules.zcgl.service.ILeaseContractInfoService;
import org.jeecg.modules.zcgl.vo.AssetInfoPage;
import org.jeecg.modules.zcgl.vo.AssetLedgerVo;
import org.jeecg.modules.zcgl.vo.statistical.AssetsParameterVo;
import org.jeecg.modules.zcgl.vo.statistical.AssetsParameterStatisticalVo;
import org.jeecgframework.poi.excel.annotation.Excel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * @Description: 资产信息
 * @Author: jeecg-boot
 * @Date: 2020-06-19
 * @Version: V1.0
 */
@Service
public class AssetInfoServiceImpl extends ServiceImpl<AssetInfoMapper, AssetInfo> implements IAssetInfoService {

    @Autowired
    private AssetInfoMapper assetInfoMapper;
    @Autowired
    private AssetInfoSubMapper assetInfoSubMapper;
    @Autowired
    private IAssetInfoSubService assetInfoSubService;
    @Autowired
    private AssetImageMapper assetImageMapper;
    @Autowired
    private ILeaseContractInfoService leaseContractInfoService;
    @Autowired
    private CustomerInfoMapper customerInfoMapper;
    @Autowired
    private SysConfigMapper sysConfigMapper;
    @Autowired
    private IAssetContractLogService assetContractLogService;
    @Autowired
    private IEncodingRulesService encodingRulesService;

    @Override
    @Transactional
    public void saveMain(AssetInfoPage assetInfoPage) {
        //检测数据，插入资产信息
        this.checkModel(assetInfoPage);

        AssetInfo assetInfo = new AssetInfo();
        BeanUtils.copyProperties(assetInfoPage, assetInfo);


        String isApproval = sysConfigMapper.getValueByKey(CommonConstant.IS_APPROVAL);
        if ("1".equals(isApproval)) {
            assetInfo.setStatus(AssetStatusEnum.DRAFT.getStatus());
        }
        assetInfoMapper.insert(assetInfo);

        //插入资产详情，并修改资产状态信息
        this.saveSub(assetInfo, assetInfoPage.getAssetInfoSubList());

        //插入资产图片信息
        this.saveImageList(assetInfo, assetInfoPage.getAssetImageList());

    }
//
//    @Override
//    public void importSaveMain(AssetInfoPage assetInfoPage) {
//
//        AssetInfo assetInfo = new AssetInfo();
//        BeanUtils.copyProperties(assetInfoPage, assetInfo);
//
//        if (StringUtils.isBlank(assetInfo.getAssetName())) {
//            throw new JeecgBootException("资产名称不能为空");
//        }
//        if (StringUtils.isBlank(assetInfo.getAssetCode())) {
//            throw new JeecgBootException("资产编码不能为空");
////            assetInfo.setAssetCode(this.getCode());
//        }
//        LambdaQueryWrapper<AssetInfo> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(AssetInfo::getAssetCode, assetInfoPage.getAssetCode());
//        queryWrapper.last("LIMIT 1");
//        AssetInfo a = assetInfoMapper.selectOne(queryWrapper);
//        if (a != null) {
////            throw new JeecgBootException("【" + assetInfo.getAssetCode() + "】资产编码已存在");
//            BeanUtils.copyProperties(assetInfo, a, ModelUtil.getNullPropertyNames(assetInfo));
//            assetInfo = a;
//        }
//
//        String isApproval = sysConfigMapper.getValueByKey(CommonConstant.IS_APPROVAL);
//        if (!"1".equals(isApproval)) {
//            assetInfo.setStatus(AssetStatusEnum.FOR_RENT.getStatus());
//        } else {
//            assetInfo.setStatus(AssetStatusEnum.DRAFT.getStatus());
//        }
//        super.saveOrUpdate(assetInfo);
//
//        if (assetInfoPage.getAssetInfoSubList() != null) {
//
//            for (AssetInfoSub entity : assetInfoPage.getAssetInfoSubList()) {
//                if (StringUtils.isBlank(entity.getRoomName())) {
//                    continue;
//                }
//                LambdaQueryWrapper<AssetInfoSub> qw = new LambdaQueryWrapper<>();
//                qw.eq(AssetInfoSub::getAssetInfoId, assetInfo.getId());
//                qw.eq(AssetInfoSub::getRoomName, entity.getRoomName());
//                if (StringUtils.isNotBlank(entity.getId())) {
//                    qw.ne(AssetInfoSub::getId, entity.getId());
//                }
//                qw.last(" LIMIT 1");
//                AssetInfoSub sub = assetInfoSubMapper.selectOne(qw);
//                if (sub != null) {
//                    BeanUtils.copyProperties(entity, sub, ModelUtil.getNullPropertyNames(entity));
//                    entity = sub;
//                }
//                //外键设置
//                entity.setRoomStatus(AssetStatusEnum.FOR_RENT.getStatus());
//                entity.setAssetInfoId(assetInfo.getId());
//                assetInfoSubService.saveOrUpdate(entity);
//            }
//        }
//
//
//    }

    @Override
    @Transactional
    public void updateMain(AssetInfoPage assetInfoPage, boolean isTask) {

        if (StringUtils.isBlank(assetInfoPage.getId())) {
            throw new JeecgBootException("资产信息错误！");
        }
        AssetInfo assetInfo = baseMapper.selectById(assetInfoPage.getId());
        if (assetInfo == null) {
            throw new JeecgBootException("资产不存在！");
        }

        String isApproval = sysConfigMapper.getValueByKey(CommonConstant.IS_APPROVAL);
        if (!isTask) {
            if (assetInfo.getStatus() == null || assetInfo.getStatus().intValue() != AssetStatusEnum.DRAFT.getStatus()) {
                if ("1".equals(isApproval) &&
                        (assetInfo.getProcessStatus() == null
                                || ResultEnum.RESULT_PASS.getStatus() != assetInfo.getProcessStatus().intValue())) {
                    throw new JeecgBootException("未审批通过，不能编辑！");
                }
            }
        }

        this.checkModel(assetInfoPage);
        if (!isTask && assetInfo.getStatus().intValue() == AssetStatusEnum.DRAFT.getStatus() && "1".equals(isApproval)){
            assetInfoPage.setStatus(AssetStatusEnum.DRAFT.getStatus());
        }
//        AssetInfo assetInfo = new AssetInfo();
//        BeanUtils.copyProperties(assetInfoPage, assetInfo, ReflectHelper.getFiledName(BaseEntity.class));
        BeanUtils.copyProperties(assetInfoPage, assetInfo);
        //当前明细
        List<AssetInfoSub> assetInfoSubList = assetInfoPage.getAssetInfoSubList();
        //原明细
        List<AssetInfoSub> oldAssetInfoSubList = assetInfoSubMapper.selectByMainId(assetInfo.getId());
        boolean oldSubBool = oldAssetInfoSubList != null && !oldAssetInfoSubList.isEmpty(),
                subBool = assetInfoSubList != null && !assetInfoSubList.isEmpty();
        //原来没有明细，后面加的明细，判断是否有合同存在
        if (!oldSubBool && subBool) {
            int num = assetContractLogService.countNum(assetInfo.getId(), null, null, YesNoEnum.NO.getStatus());
            if (num > 0) {
                throw new JeecgBootException("资产有进行中的合同，不能直接添加明细，请先确定签订中的合同信息！");
            }
        } else if (oldSubBool) {
            if (subBool) {
                //判断去掉新的明细有的资产明细信息
                for (AssetInfoSub sub : assetInfoSubList) {
                    oldAssetInfoSubList.removeIf(oldSub -> oldSub.getId().equalsIgnoreCase(sub.getId()));
                }
            }
            //遍历被删除的资产明细
            oldAssetInfoSubList.stream().forEach(oldSub -> {
                //查询进行中的合同
                int num = assetContractLogService.countNum(assetInfo.getId(), null, oldSub.getId(), YesNoEnum.NO.getStatus());
                if (num > 0) {
                    throw new JeecgBootException(oldSub.getRoomName() + "：有进行中的合同，不能删除，请先确定签订中的合同信息！");
                }
                //查询是否签订过合同，如果签订过合同进行逻辑删除，后面就不会物理删除
                int num1 = assetContractLogService.countNum(assetInfo.getId(), null, oldSub.getId(), null);
                if (num1 > 0) {
                    assetInfoSubMapper.deleteById(oldSub.getId());
//                    throw new JeecgBootException(oldSub.getRoomName() + "：已签订过合同，不能删除！");
                }
            });
        }

        BeanUtils.copyProperties(assetInfoPage, assetInfo);
        assetInfoMapper.updateById(assetInfo);
        //1.先删除子表数据
        assetInfoSubMapper.deletePhysicalByMainId(assetInfo.getId());
        //2.子表数据重新插入
        this.saveSub(assetInfo, assetInfoSubList);

        //3.先删除资产图片然后重新插入资产图片
        assetImageMapper.deletePhysicalByMainId(assetInfo.getId());
        this.saveImageList(assetInfo, assetInfoPage.getAssetImageList());
    }

    /**
     * 修改资产为闲置状态
     *
     * @param assetIds
     * @param assetSubIds
     */
    @Override
    @Transactional
    public void updateAssetForRentStatus(String assetIds, String assetSubIds) {

        if (StringUtils.isNotBlank(assetSubIds)) {
            List<AssetInfoSub> assetInfoSubList = assetInfoSubService.listByIds(Arrays.asList(assetSubIds.split(CommonConstant.DEFAULT_SEPARATOR)));
            //循环判断资产房间信息并更新
            assetInfoSubList.stream().forEach(sub -> {
                //查询出租数量
                int hasContractQuantity = assetContractLogService.countNum(null, null, sub.getId(), YesNoEnum.NO.getStatus());
                sub.setHasContractQuantity(hasContractQuantity);
                sub.setLastRentEndTime(assetContractLogService.selectMaxRentEndTimeByKey(sub.getAssetInfoId(), null, sub.getId(), YesNoEnum.NO.getStatus()));
                sub.setRoomStatus(hasContractQuantity == 0 ? AssetStatusEnum.FOR_RENT.getStatus() : AssetStatusEnum.LEASE_OUT.getStatus());
                assetInfoSubService.updateById(sub);
            });
        }


        if (StringUtils.isNotBlank(assetIds)) {
            List<AssetInfo> assetList = super.listByIds(Arrays.asList(assetIds.split(CommonConstant.DEFAULT_SEPARATOR)));
            //循环判断资产信息并更新
            assetList.stream().forEach(assetInfo -> {
                //查询出租数量
                int hasContractQuantity = assetContractLogService.countNum(assetInfo.getId(), null, null, YesNoEnum.NO.getStatus());
                assetInfo.setLastRentEndTime(assetContractLogService.selectMaxRentEndTimeByKey(assetInfo.getId(), null, null, YesNoEnum.NO.getStatus()));
                assetInfo.setHasContractQuantity(hasContractQuantity);
                if (hasContractQuantity == 0) {
                    assetInfo.setStatus(AssetStatusEnum.FOR_RENT.getStatus());
                } else {
                    //查询未出租资产详情信息数量
                    Integer num = assetInfoSubService.selectCountByRoomStatus(AssetStatusEnum.LEASE_OUT.getStatus(), assetInfo.getId());
                    if (num == 0) {
                        assetInfo.setStatus(AssetStatusEnum.LEASE_OUT.getStatus());
                    } else {
                        assetInfo.setStatus(AssetStatusEnum.FOR_RENT.getStatus());
                    }
                }
                super.updateById(assetInfo);
            });
        }
    }

    @Override
    @Transactional
    public void delMain(String id) {
        int num = assetContractLogService.countNum(id, null, null, null);
        if (num > 0) {
            throw new JeecgBootException("资产已签订过合同，不能删除！");
        }
        assetInfoSubMapper.deleteByMainId(id);
        assetInfoMapper.deleteById(id);
    }

    @Override
    @Transactional
    public void delBatchMain(Collection<? extends Serializable> idList) {
        for (Serializable id : idList) {
            this.delMain(id.toString());
        }
    }

    @Override
    public IPage<AssetLedgerVo> queryAssetLedgerVoList(Page<AssetLedgerVo> page, QueryWrapper<AssetLedgerVo> queryWrapper) {
        return assetInfoMapper.queryAssetLedgerVoList(page, queryWrapper);
    }

    @Override
    public List<AssetLedgerVo> queryAssetLedgerVoList(QueryWrapper<AssetLedgerVo> queryWrapper) {
        return assetInfoMapper.queryAssetLedgerVoList(queryWrapper);
    }

//    @Override
//    @Transactional
//    public boolean saveByAssetLedger(AssetLedgerVo vo) {
//
//        boolean result = false;
//        if (StringUtils.isBlank(vo.getAssetCode()) && StringUtils.isBlank(vo.getAssetName())) {
//            throw new JeecgBootException("资产编号或者资产名称必须存在一个");
//        }
//
//        //查询资产信息
//        AssetInfo aqwVo = new AssetInfo();
//        if (StringUtils.isNotBlank(vo.getAssetCode())) {
//            aqwVo.setAssetCode(vo.getAssetCode());
//        } else {
//            aqwVo.setAssetName(vo.getAssetName());
//        }
//        QueryWrapper<AssetInfo> assetInfoQueryWrapper = new QueryWrapper<>(aqwVo);
//        AssetInfo assetInfo = assetInfoMapper.selectOne(assetInfoQueryWrapper);
//        boolean bool = false;
//        if (assetInfo == null) {
//            assetInfo = new AssetInfo();
//            BeanUtils.copyProperties(vo, assetInfo);
//
//            String isApproval = sysConfigMapper.getValueByKey(CommonConstant.IS_APPROVAL);
//            if (!"1".equals(isApproval)) {
//                assetInfo.setStatus(AssetStatusEnum.FOR_RENT.getStatus());
//            } else {
//                assetInfo.setStatus(AssetStatusEnum.DRAFT.getStatus());
//            }
//            bool = this.retBool(assetInfoMapper.insert(assetInfo));
//            if (!bool) {
//                throw new JeecgBootException("保存资产信息失败");
//            }
//            result = true;
//        }
//        //查询资产详情信息
//        AssetInfoSub assetInfoSub = new AssetInfoSub();
//        //判断有没有门牌号，如果有查询详情是否存在保存
//        if (StringUtils.isNotBlank(vo.getRoomName())) {
//            AssetInfoSub asqwVo = new AssetInfoSub();
//            asqwVo.setAssetInfoId(assetInfo.getId());
//            asqwVo.setRoomName(vo.getRoomName());
//            QueryWrapper<AssetInfoSub> assetInfoSubQueryWrapper = new QueryWrapper<>(asqwVo);
//            assetInfoSub = assetInfoSubMapper.selectOne(assetInfoSubQueryWrapper);
//            if (assetInfoSub == null) {
//                assetInfoSub = new AssetInfoSub();
//                BeanUtils.copyProperties(vo, assetInfoSub);
//                assetInfoSub.setAssetInfoId(assetInfo.getId());
//                bool = this.retBool(assetInfoSubMapper.insert(assetInfoSub));
//                if (!bool) {
//                    throw new JeecgBootException("保存资产详细信息失败");
//                }
//                result = true;
//            }
//        } else {
//            //如果没有门牌号信息，查询看资产是否有详情，如果有详情抛出异常，必须添加门牌号
//            LambdaQueryWrapper<AssetInfoSub> assetInfoSubLambdaQueryWrapper = new LambdaQueryWrapper<>();
//            assetInfoSubLambdaQueryWrapper.eq(AssetInfoSub::getAssetInfoId, assetInfo.getId());
//            Integer subNum = assetInfoSubMapper.selectCount(assetInfoSubLambdaQueryWrapper);
//            if (subNum == null && subNum.intValue() > 0) {
//                throw new JeecgBootException("该资产必须有资产详情（门牌号）");
//            }
//        }
//
//        CustomerInfo customerInfo = new CustomerInfo();
//        //判断是否有客户信息
//        if (StringUtils.isNotBlank(vo.getCode()) || StringUtils.isNotBlank(vo.getName()) || StringUtils.isNotBlank(vo.getPhone())) {
//            //对有客户信息的，查询客户信息
//            CustomerInfo cqwVo = new CustomerInfo();
//            if (StringUtils.isNotBlank(vo.getCode())) {
//                cqwVo.setCode(vo.getCode());
//            } else {
//                cqwVo.setName(vo.getName());
//                cqwVo.setPhone(vo.getPhone());
//            }
//            QueryWrapper<CustomerInfo> customerInfoQueryWrapper = new QueryWrapper<>(cqwVo);
//            customerInfo = customerInfoMapper.selectOne(customerInfoQueryWrapper);
//
//            if (customerInfo == null) {
//                customerInfo = new CustomerInfo();
//                BeanUtils.copyProperties(vo, customerInfo);
//                bool = this.retBool(customerInfoMapper.insert(customerInfo));
//                if (!bool) {
//                    throw new JeecgBootException("保存客户信息失败");
//                }
//                result = true;
//            }
//
//            //查询资产是否有正在执行的合同存在，如果有合同存在抛出异常
//            LambdaQueryWrapper<LeaseContractInfo> leaseContractInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
//            leaseContractInfoLambdaQueryWrapper.eq(LeaseContractInfo::getAssetId, assetInfo.getId());
//            leaseContractInfoLambdaQueryWrapper.and(wrapper -> wrapper.eq(LeaseContractInfo::getStatus, LeaseContractStatusEnum.TAKE_EFFECT.getStatus())
//                    .or().eq(LeaseContractInfo::getStatus, LeaseContractStatusEnum.RENEW.getStatus()));
//            if (StringUtils.isNotBlank(assetInfoSub.getId())) {
//                leaseContractInfoLambdaQueryWrapper.like(LeaseContractInfo::getAssetSubIds, assetInfoSub.getId());
//            }
//            Integer rakeNum = leaseContractInfoService.count(leaseContractInfoLambdaQueryWrapper);
//            if (rakeNum != null && rakeNum.intValue() > 0) {
//                throw new JeecgBootException("该资产已签订合同，不能导入合同信息");
//            }
//
//            if (StringUtils.isNotBlank(vo.getContractNum())) {
//                LambdaQueryWrapper<LeaseContractInfo> leaseContractInfoLambdaQueryWrapper1 = new LambdaQueryWrapper<>();
//                leaseContractInfoLambdaQueryWrapper1.eq(LeaseContractInfo::getContractNum, vo.getContractNum());
//                Integer contractNum = leaseContractInfoService.count(leaseContractInfoLambdaQueryWrapper);
//                if (contractNum != null && contractNum.intValue() > 0) {
//                    throw new JeecgBootException("合同编号已存在");
//                }
//            }
//
//            //添加合同信息
//            LeaseContractInfo leaseContractInfo = new LeaseContractInfo();
//            BeanUtils.copyProperties(vo, leaseContractInfo);
//            if (StringUtils.isNotBlank(assetInfoSub.getId())) {
//                leaseContractInfo.setAssetSubIds(assetInfoSub.getId());
//            } else {
//                leaseContractInfo.setAssetSubIds(null);
//            }
//            leaseContractInfo.setAssetId(assetInfo.getId());
//            leaseContractInfo.setCustomerId(customerInfo.getId());
//            leaseContractInfo.setStatus(LeaseContractStatusEnum.DRAFT.getStatus());
//            bool = leaseContractInfoService.save(leaseContractInfo);
//            if (!bool) {
//                throw new JeecgBootException("保存合同信息失败");
//            }
//            result = true;
//
//        }
//
//        return result;
//    }

    @Override
    public BigDecimal queryTotalAreaByIds(String ids) {
        return baseMapper.queryTotalAreaByIds(ids);
    }

    /**
     * 检测实体验证
     *
     * @param assetInfoPage
     */
    @Override
    public void checkModel(AssetInfoPage assetInfoPage) {
        if (StringUtils.isBlank(assetInfoPage.getAssetName())) {
            throw new JeecgBootException("资产名称不能为空！");
        }
//        if (StringUtils.isBlank(assetInfoPage.getAssetCode())) {
//            throw new JeecgBootException("资产编码不能为空！");
//            assetInfo.setAssetCode(this.getCode());
//        }
        boolean assetIdBool = StringUtils.isNotBlank(assetInfoPage.getId());
        LambdaQueryWrapper<AssetInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AssetInfo::getAssetName, assetInfoPage.getAssetName());
        if (assetIdBool) {
            queryWrapper.ne(AssetInfo::getId, assetInfoPage.getId());
        }
        queryWrapper.last("LIMIT 1");
        AssetInfo a = assetInfoMapper.selectOne(queryWrapper);
        if (a != null){
            throw new JeecgBootException("资产名称已存在！");
        }

//        assetInfoPage.setAssetCode(this.getAssetCodeAndCheck(assetInfoPage.getAssetCode(), assetInfoPage.getId(), assetInfoPage.getAssetClass(), assetInfoPage.getCompanyId()));

        if (assetInfoPage.getStatus() == null || assetInfoPage.getStatus().intValue() == 0) {
            assetInfoPage.setStatus(AssetStatusEnum.FOR_RENT.getStatus());
        }
        List<String> subNames = new ArrayList<>();
        //资产的状态是否是已处置，占用，借用，其它
        boolean assetStatusBool = assetInfoPage.getStatus().intValue() >= AssetStatusEnum.ASSET_DISPOSAL.getStatus();
        List<AssetInfoSub> assetInfoSubList = assetInfoPage.getAssetInfoSubList();
        //forRentNum 闲置数量， leaseOut 出租数量
        int forRentNum = 0, leaseOut = 0;
        if (assetInfoSubList != null) {
            for (AssetInfoSub sub : assetInfoSubList) {
                if (StringUtils.isBlank(sub.getRoomName())) {
                    throw new JeecgBootException("【" + sub.getRoomName() + "】门牌号必须填写！");
                }
                if (sub.getRoomArea() == null || sub.getRoomArea().compareTo(BigDecimal.ZERO) < 1) {
                    throw new JeecgBootException("【" + assetInfoPage.getAssetName() + "-" + sub.getRoomName() + "】面积必须正确填写，大于0的数字！");
                }
                if (subNames.contains(sub.getRoomName())) {
                    throw new JeecgBootException("【" + assetInfoPage.getAssetName() + "-" + sub.getRoomName() + "】门牌号重复！");
                }
                if (assetStatusBool) {
                    sub.setRoomStatus(assetInfoPage.getStatus());
                }
                if (sub.getRoomStatus() == null) {
                    sub.setRoomStatus(AssetStatusEnum.FOR_RENT.getStatus());
                }
                if (StringUtils.isNotBlank(assetInfoPage.getId())) {
                    //查询出租数量
                    int hasContractQuantity = assetContractLogService.countNum(null, null, sub.getId(), YesNoEnum.NO.getStatus());
                    if (hasContractQuantity > 0 && assetStatusBool) {
                        throw new JeecgBootException("【" + assetInfoPage.getAssetName() + "】资产明细有合同信息，资产状态错误！");
                    }
                    if (hasContractQuantity != 0 && sub.getRoomStatus().intValue() == AssetStatusEnum.FOR_RENT.getStatus()) {
                        sub.setRoomStatus(AssetStatusEnum.LEASE_OUT.getStatus());
                    } else if (hasContractQuantity != 0 && sub.getRoomStatus().intValue() != AssetStatusEnum.LEASE_OUT.getStatus()
                            && sub.getRoomStatus().intValue() != AssetStatusEnum.ASSET_DISPOSALING.getStatus()) {
                        throw new JeecgBootException("【" + assetInfoPage.getAssetName() + "-" + sub.getRoomName() + "】资产有合同信息，资产状态必须是" + AssetStatusEnum.LEASE_OUT.getName() + "状态！");
                    }
                    //如果资产明细选择的已出租，但是没有合同信息，重置资产为闲置
                    if (sub.getRoomStatus().intValue() == AssetStatusEnum.LEASE_OUT.getStatus() && hasContractQuantity == 0) {
                        sub.setRoomStatus(AssetStatusEnum.FOR_RENT.getStatus());
                    }
                } else {
                    //添加资产明细选择的已出租，重置资产为闲置
                    if (sub.getRoomStatus().intValue() == AssetStatusEnum.LEASE_OUT.getStatus()) {
                        sub.setRoomStatus(AssetStatusEnum.FOR_RENT.getStatus());
                    }
                }
                if (sub.getRoomStatus().intValue() == AssetStatusEnum.LEASE_OUT.getStatus()) {
                    ++leaseOut;
                } else if (sub.getRoomStatus().intValue() == AssetStatusEnum.FOR_RENT.getStatus()) {
                    ++forRentNum;
                }
            }
            assetInfoPage.setHasSubQuantity(assetInfoSubList.size());
        } else {
            assetInfoPage.setHasSubQuantity(0);
        }
        //如果是不能出租的资产，检测出租状态

        //出租数量
        int hasContractQuantity = 0;
        if (assetIdBool) {
            hasContractQuantity = assetContractLogService.countNum(assetInfoPage.getId(), null, null, YesNoEnum.NO.getStatus());
            assetInfoPage.setHasContractQuantity(hasContractQuantity);
            if (assetStatusBool && hasContractQuantity > 0) {
                throw new JeecgBootException("【" + assetInfoPage.getAssetName() + "】资产有合同存在，资产状态有误！");
            }
        }
        if (!assetStatusBool) {
            //处置中的资产已签订的合同忽略
            if (assetInfoPage.getStatus().intValue() <= AssetStatusEnum.LEASE_OUT.getStatus()){
                if (forRentNum > 0 && leaseOut > 0) {
                    assetInfoPage.setStatus(AssetStatusEnum.PART_RENT.getStatus());
                } else if (leaseOut > 0) {
                    assetInfoPage.setStatus(AssetStatusEnum.LEASE_OUT.getStatus());
                } else if (forRentNum == 0 && leaseOut == 0 && assetIdBool) {
                    assetInfoPage.setStatus(hasContractQuantity > 0 ? AssetStatusEnum.LEASE_OUT.getStatus() : AssetStatusEnum.FOR_RENT.getStatus());
                } else {
                    assetInfoPage.setStatus(AssetStatusEnum.FOR_RENT.getStatus());
                }
            }
        }
        //把算出来的资产状态放到初始资产状态里面
        assetInfoPage.setInitStatus(assetInfoPage.getStatus());

        assetInfoPage.setProcessDescription("");
        assetInfoPage.setProcessStatus(-1);
        assetInfoPage.setProcessStatusText("");
    }

    /**
     * 保存资产详情
     *
     * @param assetInfo
     * @param assetInfoSubList
     */
    private void saveSub(AssetInfo assetInfo, List<AssetInfoSub> assetInfoSubList) {
        if (assetInfoSubList == null) return;
        for (AssetInfoSub entity : assetInfoSubList) {
            //外键设置
            entity.setAssetInfoId(assetInfo.getId());
            assetInfoSubMapper.insert(entity);
        }
    }

    /***
     * 保存资产图片
     * @param assetInfo
     * @param assetImageList
     */
    private void saveImageList(AssetInfo assetInfo, List<AssetImage> assetImageList) {
        if (assetImageList == null) return;
        for (AssetImage entity : assetImageList) {
            entity.setAssetId(assetInfo.getId());
            assetImageMapper.insert(entity);
        }
    }

    @Override
    public String getAssetCodeAndCheck(String assetCode, String id, String dictItemValue, String companyId) {
        boolean codeBool;
        boolean isAuto = false;
        if (StringUtils.isBlank(assetCode)) {
//            throw new JeecgBootException("资产编码不能为空！");
            isAuto = true;
            assetCode = this.getAssetCode(ReflectHelper.getName(AssetInfo::getAssetClass), dictItemValue, null, companyId);
        }
        //循环获取没有重复的编码
        do {
            LambdaQueryWrapper<AssetInfo> queryWrapper = new LambdaQueryWrapper<>();
            if (StringUtils.isNotBlank(id)) {
                queryWrapper.ne(AssetInfo::getId, id);
            }
//            queryWrapper.eq(AssetInfo::getAssetCode, assetCode);
            queryWrapper.last("LIMIT 1");
            AssetInfo a = assetInfoMapper.selectOne(queryWrapper);
            if (a != null) {
                if (!isAuto) {
                    throw new JeecgBootException("【" + assetCode + "】资产编码已存在！");
                }
                assetCode = this.getAssetCode(ReflectHelper.getName(AssetInfo::getAssetClass), dictItemValue, null, companyId);
                codeBool = true;
            } else {
                codeBool = false;
            }
        } while (codeBool && isAuto);

        return assetCode;
    }

    @Override
    public String getAssetCode(String fieldName, String dictItemValue, String code, String companyId) {

        if (StringUtils.isBlank(fieldName)) {
            throw new JeecgBootException("生成编码失败，请联系系统管理员！");
        }
        Field field = ReflectHelper.getField(AssetInfo.class, fieldName);
        if (field == null) {
            throw new JeecgBootException("生成编码失败，请联系系统管理员！");
        }
        String dicCode = null;
        Excel excel = field.getAnnotation(Excel.class);
        if (excel != null) {
            dicCode = excel.dicCode();
        }
        return encodingRulesService.getNextCoding(YesNoEnum.YES.getStatus(), dicCode, dictItemValue, code, companyId);
    }

    @Override
    public IPage<AssetsParameterVo> queryAssetsParameterVoList(Page<AssetsParameterVo> page, QueryWrapper<AssetsParameterVo> queryWrapper) {
        return baseMapper.queryAssetsParameterVoList(page,queryWrapper);
    }

    @Override
    public List<AssetsParameterVo> queryAssetsParameterVoList(QueryWrapper<AssetsParameterVo> queryWrapper) {
        return baseMapper.queryAssetsParameterVoList(queryWrapper);
    }

    @Override
    public AssetInfo getByContractNum(String contractNum) {
        return baseMapper.getByContractNum(contractNum);
    }

    @Override
    public IPage<AssetsParameterStatisticalVo> queryAssetsParameterStatisticalPageList(Page<AssetsParameterStatisticalVo> page, QueryWrapper<AssetsParameterStatisticalVo> queryWrapper) {
        return baseMapper.queryAssetsParameterStatisticalPageList(page,queryWrapper);
    }

}
